package xyz.zhzby.cyzx.servicebase.domain;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @author zby
 * @date 2021/12/06
 */
@ApiModel("分页结果集")
public class PageResponse<T> implements Iterable<T>, Serializable {

    @ApiModelProperty("数据列表")
    private List<T> items = new ArrayList<>();

    @ApiModelProperty("数据记录总数")
    private long counts;

    @ApiModelProperty("当前页码")
    @NotNull(message = "页码不能为空")
    @Min(value = 1, message = "页码最小为1，默认第一页开始")
    private long page;

    @ApiModelProperty("一页数据数")
    @NotNull
    @Min(value = 1, message = "最小为1，默认为10")
    private long pageSize;

    public PageResponse() {
        this.page = 1L;
        this.pageSize = 10L;
    }

    public PageResponse(long total, long page, long pageSize) {
        this.counts = total;
        this.page = page;
        this.pageSize = pageSize;
    }

    public PageResponse(List<T> items, long counts, long page, long pageSize) {
        this.items = items;
        this.counts = counts;
        this.page = page;
        this.pageSize = pageSize;
    }

    public boolean hasPrevious() {
        return this.getPage() > 0L;
    }

    public boolean hasNext() {
        return this.getPage() + 1L < this.getPages();
    }

    public boolean isFirst() {
        return !this.hasPrevious();
    }

    boolean isLast() {
        return !this.hasNext();
    }

    public long getCounts() {
        return this.counts;
    }

    public void setCounts(long counts) {
        this.counts = counts;
    }

    @ApiModelProperty("总页数")
    public long getPages() {
        return this.getPageSize() == 0L ? 1L : (long) ((int) Math.ceil((double) this.counts / (double) this.getPageSize()));
    }

    public List<T> getItems() {
        return Collections.unmodifiableList(this.items);
    }

    public void setItems(List<T> items) {
        this.items = items;
    }

    public boolean hasItems() {
        return this.getItemsSize() > 0;
    }

    public int getItemsSize() {
        return this.items.size();
    }

    public long getPageSize() {
        return this.pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = (long) pageSize;
    }

    public long getPage() {
        return this.page;
    }

    public void setPage(int page) {
        this.page = (long) page;
    }

    @Override
    public Iterator<T> iterator() {
        return this.getItems().iterator();
    }
}
